#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import re
from docx import Document
from docx.shared import Pt
from docx.oxml.ns import qn
from docx.oxml import OxmlElement
from pypinyin import pinyin, Style

class WordPinyin:
    def __init__(self):
        # 简单的汉字到拼音映射表（示例）
        # 实际应用中可能需要使用更完整的拼音库
        pass
    def is_chinese_char(self, char):
        """判断字符是否为中文字符"""
        return '\u4e00' <= char <= '\u9fff'

    
    def add_pinyin_to_char(self, run, char,pinyin,pinyinfont='SimSun'):
        """为单个汉字添加注音"""
        if not pinyin:
            run.text = char
            return
        
        # 创建一个新的字段（field）
        fld_char_begin = OxmlElement('w:fldChar')
        fld_char_begin.set(qn('w:fldCharType'), 'begin')
        
        instr_text = OxmlElement('w:instrText')
        # 设置EQ域代码，用于显示注音
        # 格式: EQ \* jc0 \* "Font:SimSun" \* hps14 \o \ad(\s \up 13(拼音),汉字)
        instr_text.text = f' EQ \* jc0 \* "Font:{pinyinfont}" \* hps14 \\o \\ad(\\s \\up 13({pinyin}),{char})'
        
        fld_char_separate = OxmlElement('w:fldChar')
        fld_char_separate.set(qn('w:fldCharType'), 'separate')
        
        fld_char_end = OxmlElement('w:fldChar')
        fld_char_end.set(qn('w:fldCharType'), 'end')
        
        # 清除原run的文本
        run.text = ''
        
        # 将字段添加到run中
        run._r.append(fld_char_begin)
        run._r.append(instr_text)
        run._r.append(fld_char_separate)
        run._r.append(fld_char_end)
    
    def process_document(self, input_file, output_file=None):
        """处理Word文档，为汉字添加注音"""
        if not os.path.exists(input_file):
            raise FileNotFoundError(f"找不到文件: {input_file}")
        
        # 如果未指定输出文件，则在原文件名基础上加"_with_pinyin"后缀
        if output_file is None:
            base_name, ext = os.path.splitext(input_file)
            output_file = f"{base_name}_with_pinyin{ext}"
        
        # 打开文档
        doc = Document(input_file)
        
        # 遍历所有段落
        for paragraph in doc.paragraphs:
            # 保存原始段落的样式
            original_style = paragraph.style
            
            # 保存原始段落中的所有run
            original_runs = list(paragraph.runs)
            
            # 清空段落
            paragraph.clear()
            
            # 重新设置段落样式
            paragraph.style = original_style
            
            # 处理每个run
            for run in original_runs:
                # 获取原始run的文本、字体、大小等属性
                text = run.text
                font_name = run.font.name
                font_size = run.font.size
                font_bold = run.font.bold
                font_italic = run.font.italic
                font_underline = run.font.underline
                
                pinyin_list=pinyin(text, heteronym=True, errors='ignore')
                pyl_i=0

                # 遍历文本中的每个字符
                for char in text:
                    # 创建新的run
                    new_run = paragraph.add_run()
                    # 复制原始run的属性
                    if font_name:
                        new_run.font.name = font_name
                    if font_size:
                        new_run.font.size = font_size
                    new_run.font.bold = font_bold
                    new_run.font.italic = font_italic
                    new_run.font.underline = font_underline
                    
                    # 为中文字符添加注音
                    if self.is_chinese_char(char):
                        self.add_pinyin_to_char(new_run, char,pinyin_list[pyl_i][0],font_name)
                        pyl_i+=1
                    else:
                        new_run.text = char
        
        # 保存文档
        doc.save(output_file)
        print(f"已成功添加注音并保存至: {output_file}")
        return output_file

if __name__ == "__main__":
    wp = WordPinyin()
    
    # 创建示例文档
    sample_file = "Chinese.docx"
    
    # 为示例文档添加注音
    output_file = wp.process_document(sample_file)
    print("操作完成！")